package com.atguigu.lease.common.utils;

import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import io.jsonwebtoken.security.SignatureException;
import org.springframework.util.StringUtils;

import javax.crypto.SecretKey;
import java.util.Date;

/**
 * ClassName: JwtUtil
 * Package: com.atguigu.lease.common.utils
 * Description:
 *
 * @Author 咚咚小圆帽
 * @Create 2025/2/22 14:52
 * @Version 1.0
 */
public class JwtUtil {

    private static Long expireTime = 1000 * 60 * 60L;
    private static SecretKey secretKey = Keys.hmacShaKeyFor("Q5do9TZ8A894GqUbQJA5wqaqyptwzthF".getBytes());

    public static String createToken(Long userId, String username) {


        //"alg":"HS256"
        //"typ":"JWT"

        String token = Jwts.builder()
                //可以不设置，默认就是这个值
                //1.头
                .setHeaderParam("alg", "HS256")
                .setHeaderParam("typ", "JWT")
                //2.负载
                .setSubject("USER_INFO")
                //设置过期时间为1小时
                .setExpiration(new Date(System.currentTimeMillis() + expireTime))
                .claim("userId", userId)
                .claim("username", username)
                //3.秘钥
                .signWith(secretKey, SignatureAlgorithm.HS256)
                .compact();

        return token;
    }

    public static Claims parseToken(String token) {
        Claims body = null;
        try {
            body = Jwts.parserBuilder()
                    .setSigningKey(secretKey)
                    .build()
                    .parseClaimsJws(token)
                    .getBody();
        } catch (ExpiredJwtException e) {
            throw new LeaseException(ResultCodeEnum.TOKEN_EXPIRED);
        } catch (Exception e) {
            throw new LeaseException(ResultCodeEnum.TOKEN_INVALID);
        }

        //返回负载
        return body;
    }

    public static void main(String[] args) {
        String token = createToken(1L, "admin");
        System.out.println(token);

        Claims claims = parseToken(token);
        Long userId = claims.get("userId", Long.class);
        String username = claims.get("username", String.class);
        System.out.println(userId);
        System.out.println(username);

    }

}
